package com.ruoyi.gis.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gis.domain.PollutionsourceGisVO;
import com.ruoyi.gis.mapper.PollutionsourceGisMapper;
import com.ruoyi.gis.service.PollutionsourceGisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PollutionsourceGisServiceImpl implements PollutionsourceGisService {

    @Autowired
    private PollutionsourceGisMapper pollutionsourceGisMapper;


    @Override
    public List<Map<String, Object>> getPollutionsourceInfo(PollutionsourceGisVO vo) {
        return pollutionsourceGisMapper.getPollutionsourceInfo(vo);
    }

    @Override
    public List<Map<String, Object>> getPollutionsourceRealTimeData(PollutionsourceGisVO vo) {

        List<Map<String, Object>> mapList = pollutionsourceGisMapper.getPollutionsourceRealTimeData(vo);
        List<Map<String, Object>> lsit=new ArrayList<>();
        List<Map<String, Object>> itemlist=new ArrayList<>();
        Map<String, Object> s=new HashMap<>();
        s.put("pollutantCode","001");
        s.put("pollutantName","pH值");
        itemlist.add(s);
        Map<String, Object> s1=new HashMap<>();
        s1.put("pollutantCode","011");
        s1.put("pollutantName","COD");
        itemlist.add(s1);
        Map<String, Object> s2=new HashMap<>();
        s2.put("pollutantCode","060");
        s2.put("pollutantName","氨氮");
        itemlist.add(s2);
        Map<String, Object> s3=new HashMap<>();
        s3.put("pollutantCode","011");
        s3.put("pollutantName","COD");
        itemlist.add(s3);
        Map<String, Object> s4=new HashMap<>();
        s4.put("pollutantCode","065");
        s4.put("pollutantName","总氮");
        itemlist.add(s4);
        Map<String, Object> s5=new HashMap<>();
        s5.put("pollutantCode","101");
        s5.put("pollutantName","总磷");
        itemlist.add(s5);
        DecimalFormat df = new DecimalFormat("0.000");
        if(mapList!=null&&mapList.size()>0){
            for(Map<String, Object> data:mapList){
                Object avgStrength = data.get("avgStrength");
                if(avgStrength!=null&&!"".equals(avgStrength)){
                    String sse = String.valueOf(avgStrength);
                    String format = df.format(Double.valueOf(sse));
                    data.put("avgStrength",format);
                }
                lsit.add(data);
            }
        }else {
            for(Map<String, Object>  data:itemlist){
                data.put("avgStrength","");
                data.put("isOverWarn","");
                data.put("monitorTime","");
                data.put("outPortCode",vo.getOutPortCode());
                data.put("outPortName","");
                data.put("polluteID",vo.getPolluteId());
                data.put("polluteName","");
                data.put("unit","");
                lsit.add(data);
            }
        }
        return lsit;
    }

    @Override
    public List<Map<String, Object>> pollutionsourceWateroutput(PollutionsourceGisVO vo) {
        return pollutionsourceGisMapper.pollutionsourceWateroutput(vo);
    }

    @Override
    public Map<String, Object> pollutionsourceItemTrend(PollutionsourceGisVO vo) {
        Map<String, Object> maplist=new HashMap<>();
        DecimalFormat df = new DecimalFormat("0.000");


        List<Map<String, Object>> datlist=new ArrayList<>();
        if(StringUtils.isNotEmpty(vo.getPolluteId())&&StringUtils.isNotEmpty(vo.getOutPortCode())){
            vo.setBeginTime(vo.getBeginTime()+" 00:00:00");
            vo.setEndTime(vo.getEndTime()+" 23:59:59");
            List<String> hourBetweenDatetype = DateUtils.getHourBetweenDatetype(vo.getBeginTime(), vo.getEndTime(), "yyyy-MM-dd HH:mm:ss");
            List<Map<String, Object>> basRiverpollutionsourcemapList = pollutionsourceGisMapper.pollutionsourceItemTrend(vo);

            List<String> dataTime=new ArrayList<>();
            List<String> pollutantCodelist=new ArrayList<>();
            if(basRiverpollutionsourcemapList!=null&&basRiverpollutionsourcemapList.size()>0){
                for(Map<String, Object> data:basRiverpollutionsourcemapList){
                    Object pollutantCode = data.get("pollutantCode");//因子编码
                    Object monitorTime = data.get("monitorTime");//时间
                    boolean contains = dataTime.contains(monitorTime);
                    boolean pollutantCodecontains = pollutantCodelist.contains(pollutantCode);
                    if(contains){}else {
                        dataTime.add(String.valueOf(monitorTime));
                    }
                    if(pollutantCodecontains){}else {
                        pollutantCodelist.add(String.valueOf(pollutantCode));
                    }
                }
            }

            String isShowFlow1 =null;

            //根据处理完的时间和因子进行数据处理
            if(pollutantCodelist!=null&&pollutantCodelist.size()>0){
                for(String datapo:pollutantCodelist){
                    Map<String,Object> mapdata=new HashMap<>();
                    List<Map<String, Object>> sunmapsLevels =new ArrayList<>();
                    for(String datadataTime: hourBetweenDatetype){
                        Map<String,Object> dtaiem=new HashMap<>();
                        //分组数据
                        List<Map<String, Object>> sunmapsLevel = basRiverpollutionsourcemapList.stream()
                                .filter(item -> item.get("pollutantCode").equals(datapo)
                                        &&item.get("monitorTime").equals(datadataTime)
                                )
                                .collect(Collectors.toList());
                        if(sunmapsLevel!=null&&sunmapsLevel.size()>0){
                            for(Map<String, Object> datase:sunmapsLevel){
                                Object ID = datase.get("ID");//河流id
                                Object PolluteName = datase.get("PolluteName");//河流id
                                Object outPortName = datase.get("outPortName");//河流id
                                Object outPortCodes = datase.get("outPortCode");//河流名称
                                Object monitorTime = datase.get("monitorTime");//时间
                                Object avgStrength = datase.get("avgStrength");//监测值
                                Object couFlow = datase.get("couFlow");//监测值
                                Object pollutantCode = datase.get("pollutantCode");//因子编码
                                Object pollutantName = datase.get("pollutantName");//因子名称
                                String isShowFlow = datase.get("isShowFlow")==null?"1":datase.get("isShowFlow").toString();//
                                String format = df.format(avgStrength);
                                isShowFlow1 = isShowFlow;
                                String formatCouFlow = "";
                                if (null != couFlow && "" != couFlow){
                                    formatCouFlow = df.format(Double.parseDouble(couFlow.toString()));
                                }
                                Object unit = datase.get("unit");//单位
                                Object flowUnit = datase.get("flowUnit");//单位
                                mapdata.put("unit",unit);
                                mapdata.put("flowUnit",flowUnit);
                                dtaiem.put("monitorTime",monitorTime);
                                mapdata.put("pollutantName",pollutantName);
                                mapdata.put("pollutantCode",pollutantCode);
                                dtaiem.put("avgStrength",format);
                                dtaiem.put("couflow",formatCouFlow);
                                mapdata.put("polluteId",ID);
                                mapdata.put("polluteName",PolluteName);
                                mapdata.put("outPortName",outPortName);
                                mapdata.put("outPortCode",outPortCodes);
                                sunmapsLevels.add(dtaiem);
                            }
                        }else {
                            dtaiem.put("monitorTime",datadataTime);
                            dtaiem.put("avgStrength","");
                            dtaiem.put("couflow","");
                            sunmapsLevels.add(dtaiem);
                        }

                    }
                    mapdata.put("data",sunmapsLevels);
                    datlist.add(mapdata);
                }

            }

            maplist.put("dataTime",hourBetweenDatetype);
            maplist.put("pollutantCodelist",pollutantCodelist);
            maplist.put("list",datlist);
            maplist.put("isShowFlow",isShowFlow1);
        }

        return maplist;
    }

    /*
    获取污染源企业类型
     */
    @Override
    public List<Map<String, Object>> pollutionsourceenterprisetype() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> mapList = pollutionsourceGisMapper.pollutionenterpriseTypesize(map);
        List<Map<String, Object>> list=new ArrayList<>();
        DecimalFormat df = new DecimalFormat("0.00");
        if(mapList!=null&&mapList.size()>0){
            Integer size=0;
            for(Map<String, Object>  data:mapList){
                Object enterpriseType = data.get("enterpriseType");//类型
                Object size1 = data.get("size");//数量
                Object enterpriseTypeanme = data.get("enterpriseTypeanme");//类型名称
                if(size1!=null&&!"".equals(size1)){
                    Integer integer = Integer.valueOf(String.valueOf(size1));
                    size=size+integer;
                }
            }
            //根据上面获取的全部数量进行占比计算
            // 占比数量/总数 *100
            for(Map<String, Object>  data:mapList){
                Map<String, Object> datamap=new HashMap<>();
                Object enterpriseType = data.get("enterpriseType");//类型
                Object size1 = data.get("size");//数量
                Object enterpriseTypeanme = data.get("enterpriseTypeanme");//类型名称
                datamap.put("enterpriseType",enterpriseType);
                datamap.put("enterpriseTypeName",enterpriseTypeanme);
                datamap.put("enterpriseTypeSize",size1);
                if(size1!=null&&!"".equals(size1)){
                    Integer integer = Integer.valueOf(String.valueOf(size1));
                    double v = (Double.valueOf(integer) / Double.valueOf(size)) * 100;
                    String format = df.format(v);
                    datamap.put("quantityProportion",format);
                }
                list.add(datamap);
            }
        }

        return list;
    }

    @Override
    public Map<String, Object> getEnterpriseMonitorRate() {
         Map map = new HashMap<>();
//河流下的所有子河流

        Map<String, Object> mapdat=new HashMap<>();
        DecimalFormat df = new DecimalFormat("0.00");
        //获取最新时间
         Map<String, Object> pollutionsourcenewwrunewmaxtiem = pollutionsourceGisMapper.pollutionsourcenewwrunewmaxtiemv2(map);
        //daymonitorTime
        String daymonitorTime=null;
        if(pollutionsourcenewwrunewmaxtiem!=null&&pollutionsourcenewwrunewmaxtiem.size()>0){
            Object o = pollutionsourcenewwrunewmaxtiem.get("daymonitorTime");
            if(o!=null&&!"".equals(o)){
                daymonitorTime=String.valueOf(o);
            }
        }
        List<Map<String, Object>> pollutionDatasList = pollutionsourceGisMapper.pollutionDatas();
        if(StringUtils.isNotEmpty(pollutionDatasList) && pollutionDatasList.size()>0){
            //在线数量
        List<Map<String,Object>> isOnlineMonitoringEntList=pollutionDatasList.stream().filter(s->String.valueOf(s.get("isOnlineMonitoringEnt")).equals("1")).collect(Collectors.toList());
            //污水处理厂
            List<Map<String,Object>> IssewagefarmList=pollutionDatasList.stream().filter(s->String.valueOf(s.get("Issewagefarm")).equals("1")).collect(Collectors.toList());
            //工业企业
            List<Map<String,Object>> gyList=pollutionDatasList.stream().filter(s->String.valueOf(s.get("enterpriseType")).equals("0")).collect(Collectors.toList());
            //农业企业
            List<Map<String,Object>> nyList=pollutionDatasList.stream().filter(s->String.valueOf(s.get("enterpriseType")).equals("1")).collect(Collectors.toList());
           //超标的企业数量
            Map<String, Object> pollutionsourcewaterhourdatasizemapdat=new HashMap<>();
            pollutionsourcewaterhourdatasizemapdat.put("beginTime",daymonitorTime+" 00:00:00");
            pollutionsourcewaterhourdatasizemapdat.put("endTime",daymonitorTime+" 23:59:59");
            List<Map<String, Object>> cbpollutionsourcewaterhourdatasize = pollutionsourceGisMapper.cbpollutionsourcewaterhourdatasize(pollutionsourcewaterhourdatasizemapdat);


            int size = isOnlineMonitoringEntList.size();//在线总数
            int wssize = IssewagefarmList.size();//污水处理厂数量
            int cbsize = cbpollutionsourcewaterhourdatasize.size();//超标数量
            mapdat.put("dataTime",daymonitorTime);
            mapdat.put("size",size);//在线总数
            mapdat.put("wssize",wssize);//污水处理厂数量
            mapdat.put("gysize",gyList.size());//工业企业数量
            mapdat.put("nysize",nyList.size());//农业企业数量
            mapdat.put("cbsize",cbsize);//超标排放数量

            int i = size - cbsize;

            double v = 0.0;
            //达标率 =(达标学生人数/学生总人数)×100%
            if (size>0){
                v = (Double.valueOf(i) / Double.valueOf(size)) * 100;
            }
            mapdat.put("dbl",df.format(v));
        }else{
            mapdat.put("dataTime",DateUtils.dateFormat(new Date(),"yyyy-MM-dd"));
            mapdat.put("size",null);
            mapdat.put("wssize",null);
            mapdat.put("cbsize",null);
            mapdat.put("dbl",null);
            mapdat.put("gysize",null);
            mapdat.put("nysize",null);
        }

        return mapdat;
    }

    @Override
    public Map BasPollutionsourcewrwpfl() {
        Map<String, Object> listmap=new HashMap<>();
         Map map = new HashMap<>();

        //查询最新的时间
        DecimalFormat df = new DecimalFormat("0.000");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
         //获取最新时间
        Map<String, Object> pollutionsourcenewwrunewmaxtiem = pollutionsourceGisMapper.pollutionsourcenewwrunewmaxtiemv2(map);
        String daymonitorTime=null;
        if(pollutionsourcenewwrunewmaxtiem!=null&&pollutionsourcenewwrunewmaxtiem.size()>0){
            Object o = pollutionsourcenewwrunewmaxtiem.get("monitorTimemon");
            if(o!=null&&!"".equals(o)){
                daymonitorTime=String.valueOf(o);
            }

        }
        //判断如果没有最新数据就不返回数据
        if(daymonitorTime!=null&&!"".equals(daymonitorTime)){
            List<String> last12Months = DateUtils.getLast12Months(daymonitorTime);
            listmap.put("dataTime",last12Months);
            Calendar calendar = Calendar.getInstance();
            Date parse = null;
            try {
                parse = sdf.parse(daymonitorTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            calendar.setTime(parse);
            // 添加 -1 小时到当前时间
            calendar.add(Calendar.MONTH, -12);
            Date time = calendar.getTime();
            String format = sdf.format(time);
            map.put("beginTime",format);
            map.put("endTime",daymonitorTime);
            List<Map<String, Object>> mapList = pollutionsourceGisMapper.dcBasPollutionsourcewrwpflv2(map);
            List<Map<String, Object>>  list=new ArrayList<>();

            List<String>  codelist = new ArrayList<>();
            List<Map<String, Object>>  pollutantlist = new ArrayList<>();

            if(mapList!=null&&mapList.size()>0){
                for(Map<String, Object> data:mapList){
                    Object pollutantCode = data.get("pollutantCode");//因子编码
                    Object pollutantName = data.get("pollutantName");//因子名称
                    Object unit = data.get("unit");//因子单位
                    boolean contains = codelist.contains(pollutantCode);
                    if(contains){}else {
                        Map<String, Object> pollutant = new HashMap<>();
                        codelist.add(pollutantCode.toString());
                        pollutant.put("pollutantCode",pollutantCode);
                        pollutant.put("pollutantName",pollutantName);
                        pollutant.put("unit",unit);
                        pollutantlist.add(pollutant);
                    }
                }
                listmap.put("pollutantCodelist",codelist);
                //上面处理完监测因子数据
                //分组 时间 因子编码
                if(pollutantlist!=null&&pollutantlist.size()>0){
                    for(Map<String, Object> mapCode : pollutantlist){
                        //存放因子编码为第一层
                        Map<String, Object> mapdata=new HashMap<>();
                        List<Map<String, Object>>  mapdatalist=new ArrayList<>();
                        mapdata.put("pollutantCode",mapCode.get("pollutantCode"));
                        if(last12Months!=null&&last12Months.size()>0){
                            for(String dataTime:last12Months){
                                List<Map<String, Object>> sunmapsLevel = mapList.stream()
                                        .filter(item -> item.get("pollutantCode").equals(mapCode.get("pollutantCode").toString())
                                                &&item.get("monitorTime").equals(dataTime))
                                        .collect(Collectors.toList());
                                if(sunmapsLevel!=null&&sunmapsLevel.size()>0){
                                    for( Map<String, Object> data: sunmapsLevel){
                                        Map<String, Object> mapdatas=new HashMap<>();
                                        Object monitorTime = data.get("monitorTime");//月份
                                        Object avgStrength = data.get("avgStrength");//累计数据
                                        Object pollutantCode = data.get("pollutantCode");//因子编码
                                        Object unit = data.get("unit");//单位
                                        Object pollutantName = data.get("pollutantName");//因子名称
                                        mapdata.put("unit",unit);
                                        mapdata.put("pollutantName",pollutantName);
                                        if(avgStrength!=null&&!"".equals(avgStrength)){
                                            mapdatas.put("strength",df.format(avgStrength));
                                        }else {
                                            mapdatas.put("strength",avgStrength);
                                        }
                                        mapdatas.put("monitorTime",monitorTime);
                                        mapdatalist.add(mapdatas);
                                    }
                                }else {
                                    Map<String, Object> mapdatas=new HashMap<>();
                                    mapdata.put("unit",mapCode.get("unit"));
                                    mapdata.put("pollutantName",mapCode.get("pollutantName"));
                                    mapdatas.put("strength","");
                                    mapdatas.put("monitorTime",dataTime);
                                    mapdatalist.add(mapdatas);
                                }
                            }
                        }
                        mapdata.put("data",mapdatalist);
                        list.add(mapdata);
                    }
                }
                if(list!=null&&list.size()>0){
                    listmap.put("list",list);

                }
            }
        }
        return listmap;
    }
}
